//
//  SQGoodsContentViewController.m
//  pai
//
//  Created by pro on 14-11-21.
//  Copyright (c) 2014年 linjunjing. All rights reserved.
//

#import "SQGoodsContentViewController.h"
#import "SQShopRulesViewController.h"
#import "SQGoodsPayViewController.h"
#import "Global.h"
#import "SQLoginViewController.h"
#import "UIImageView+WebCache.h"

@interface SQGoodsContentViewController ()

@end

@implementation SQGoodsContentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setTitle:@"兑换"];
    
    //[self initview];
}
-(void)getInfo
{
    product_detail_t detail;
    detail.base.msgtype = 1022;
    detail.base.len = sizeof(detail);
    detail.base.error = 0;
    
    detail.product_id=self.item.product_id;
    NSLog(@"product_id:%d",detail.product_id);
    
    NSMutableData* msgData = [NSMutableData data];
    [msgData appendBytes:&detail length:sizeof(detail)];
    
    [super sendData:msgData tag:1 withHUD:YES];
}
-(void)initview
{
    NSString* namestr = [NSString stringWithUTF8String:self.item.title];
    NSInteger chanceNum = 3;
    NSString* contentstr = [NSString stringWithUTF8String:self.item.intro];
//    NSString* namestr = @"11111";
//    NSInteger chanceNum = 3;
//    NSString* contentstr = @"111111";
    NSString* imageName = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[self.imageDic objectForKey:@"detail"]];
    
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, self.MyNavigationBar.frame.origin.y+self.MyNavigationBar.frame.size.height, 320, [[UIScreen  mainScreen] bounds].size.height - 44 - self.MyNavigationBar.frame.origin.y-self.MyNavigationBar.frame.size.height)];
    [_scrollView setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
    [self.view addSubview:_scrollView];
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = NO;
    _scrollView.scrollEnabled = YES;
    
    //图片
    NSArray* imagearr = [self.imageDic objectForKey:@"detail"];
    [self titleimage:imagearr];
    NSInteger viewHeight = 320;
    
    //名称
    UILabel* nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, viewHeight, 300, 60)];
    [nameLabel setText:namestr];
    nameLabel.textAlignment = UITextAlignmentCenter;
    nameLabel.numberOfLines = 2;
    [_scrollView addSubview:nameLabel];
    viewHeight += 55;
    //显示sku
    UILabel* skuLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight, 100, 20)];
    skuLabel.text = @"商品类型：";
    [_scrollView addSubview:skuLabel];
    for (NSInteger i=0;i<self.skuArr.count; i++) {
        product_sku_t skuitem;
        [[self.skuArr objectAtIndex:i]getValue:&skuitem];
        //NSInteger x = 100+(i%3)*70;
        //NSInteger y = 250+(i/3)*30;
        NSInteger x = 100;
        NSInteger y = viewHeight+i*30;
        UIButton* skuBtn = [[UIButton alloc]initWithFrame:CGRectMake(x,y,200,30)];
        NSString* sku_name = [NSString stringWithUTF8String:skuitem.sku_name];
        [skuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        [skuBtn setTitle:sku_name forState:UIControlStateSelected];
        [skuBtn setBackgroundImage:[UIImage imageNamed:@"sku_selected"] forState:UIControlStateSelected];
        [skuBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [skuBtn setTitle:sku_name forState:UIControlStateNormal];
        [skuBtn setBackgroundImage:[UIImage imageNamed:@"sku_unselected"] forState:UIControlStateNormal];
        NSLog(@"titleLabel:%@", skuBtn.titleLabel.text);
        [skuBtn addTarget:self action:@selector(changeSku:) forControlEvents:UIControlEventTouchUpInside];
        [_scrollView addSubview:skuBtn];
        skuBtn.tag = i+1000;
    }
    viewHeight +=self.skuArr.count*30 + 10;
    //库存
    self.stockLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight, 200, 20)];
    [_scrollView addSubview:self.stockLabel];
    
    //默认价格
    self.priceLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight + 30, 200, 20)];
    [_scrollView addSubview:self.priceLabel];
    
    //积分上限
    self.pointsLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, viewHeight+60, 200, 20)];
    [_scrollView addSubview:self.pointsLabel];
    
    //规则按钮
    UIButton* ruleBtn = [[UIButton alloc]initWithFrame:CGRectMake(230, viewHeight, 75, 75)];
    [ruleBtn setBackgroundImage:[UIImage imageNamed:@"rule_btn"] forState:UIControlStateNormal];
    [ruleBtn addTarget:self action:@selector(onActionRules:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:ruleBtn];
    viewHeight +=100;
    
    //显示sku
    UIButton *btn = (UIButton *)[_scrollView viewWithTag:1000];
    [self changeSku:btn];
    
    self.buyButton = [[UIButton alloc]initWithFrame:CGRectMake(80, viewHeight, 160, 40)];
    if (chanceNum > 0) {
        [self.buyButton setBackgroundColor:[UIColor redColor]];
        [self.buyButton setTitle:@"兑换" forState:UIControlStateNormal];
    }
    else
    {
        [self.buyButton setBackgroundColor:[UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1]];
        [self.buyButton setTitle:@"无法兑换" forState:UIControlStateDisabled];
        //self.buyButton.state = [UIControlState UIControlStateDisabled];
    }
    [self.buyButton addTarget:self action:@selector(onActionBuy:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:self.buyButton];
    viewHeight+=50;
    
    //商品详情
    UILabel* titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, viewHeight, 320, 30)];
    [titleLabel setText:@"  商品详情"];
    [titleLabel setBackgroundColor:[UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1]];
    [titleLabel setTextColor:[UIColor whiteColor]];
    titleLabel.textAlignment = UITextAlignmentLeft;
    [_scrollView addSubview:titleLabel];
    viewHeight+=30;
    
    UILabel* contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, viewHeight, 300, 200)];
    [contentLabel setNumberOfLines:0];
    [contentLabel setTextColor:[UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1]];
    [contentLabel setFont:[UIFont systemFontOfSize:14]];
    [contentLabel setText:contentstr];
    [contentLabel sizeToFit];
    [_scrollView addSubview:contentLabel];
    
    self.imageheight = contentLabel.frame.origin.y+contentLabel.frame.size.height+10;
    
    if (self.imageUrls.count > 0) {
        self.imageindex = 0;
        [self loadimage];
    }
    
    _scrollView.contentSize = CGSizeMake(320,self.imageheight);
}
-(void)titleimage:(NSArray*)arr
{
    _imagescrolView = [[UIScrollView alloc] init];
    [_imagescrolView setFrame:CGRectMake(0, 0, 320, 320)];
    [_imagescrolView setContentSize:CGSizeMake(320*arr.count, 320)];
    _imagescrolView.pagingEnabled = YES;
    _imagescrolView.delegate = self;
    _imagescrolView.bounces = NO;
    [_scrollView addSubview:_imagescrolView];
    
    for(int i=0;i<arr.count;i++)
    {
        UIImageView *imageView = [[UIImageView alloc] init];
        NSString* url = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[arr objectAtIndex:i]];
        [imageView setImageWithURL:[NSURL URLWithString:url]];
        imageView.frame = CGRectMake(320*i, 0, 320, 320);
        [_imagescrolView addSubview:imageView];
        
    }
    _page=[[UIPageControl alloc]initWithFrame:CGRectMake(250, 280, 100, 30)];
    //设置有多少个小白点
    _page.numberOfPages=arr.count;
    //设置背景色
    //page.backgroundColor=[UIColor redColor];
    //设置起始小白点是哪个
    _page.currentPage=0;
    //设置小白颜色
    _page.pageIndicatorTintColor=[UIColor greenColor];
    _page.currentPageIndicatorTintColor=[UIColor yellowColor];
    [_scrollView addSubview:_page];
    
    //通常广告是自己动
    _imageTimer=[NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(timerClick) userInfo:nil repeats:YES];
}
-(void)timerClick
{
    CGPoint point = _imagescrolView.contentOffset;
    if (point.x==_imagescrolView.contentSize.width - 320) {
        [UIView animateWithDuration:0.5 animations:^{
            _imagescrolView.contentOffset = CGPointMake(0, 0);
        }];
        _page.currentPage=0;
    }else
    {
        [UIView animateWithDuration:0.5 animations:^{
            _imagescrolView.contentOffset = CGPointMake(point.x+320, 0);
        }];
        _page.currentPage =(int)(point.x+320)/320;
    }
}
-(void)loadimage
{
    UIImageView* imgView = [[UIImageView alloc]init];
    NSString* imageUrl = [NSString stringWithFormat:@"%@%@",IMAGESERVICE,[self.imageUrls objectAtIndex:self.imageindex]];
    [imgView setImageWithURL:[NSURL URLWithString:imageUrl] placeholderImage:nil completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType)
     
     {
         __block UIImageView *tempview = imgView;
         int x=image.size.width;
         int y=image.size.height;
         CGFloat height = 320.0/x*y;
         //自适应图片宽高比例
         tempview.frame = CGRectMake(0, self.imageheight, 320, height);
         tempview.contentMode = UIViewContentModeScaleAspectFit;
         self.imageheight += height;
         _scrollView.contentSize = CGSizeMake(320,self.imageheight+10);
         if (self.imageindex < self.imageUrls.count - 1) {
             self.imageindex ++;
             [self loadimage];
         }
     }];
    [_scrollView addSubview:imgView];
}
-(void)changeSku:(id)sender
{
    UIButton* btn = (UIButton*)sender;
    //切换选中状态
    for (NSInteger i=0; i<self.skuArr.count; i++) {
        UIButton *skubtn = (UIButton *)[_scrollView viewWithTag:i+1000];
        skubtn.selected = NO;
        NSLog(@"%d",skubtn.tag);
    }
    btn.selected = YES;
//    NSLog(@"%@",btn.titleLabel.text);
    NSLog(@"%d",btn.tag);
    self.selectedSku = btn.tag -1000;
    product_sku_t skuitem;
    [[self.skuArr objectAtIndex:self.selectedSku]getValue:&skuitem];
    //库存
    NSMutableAttributedString* stock = [[NSMutableAttributedString alloc]initWithString:[[NSString alloc] initWithFormat:@"商品库存：%d件",skuitem.stock]];
    [stock addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,5)];
    [stock addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5,[stock length]-6)];
    [stock addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange([stock length]-1,1)];
    self.stockLabel.attributedText = stock;
    //价格
    NSMutableAttributedString* price = [[NSMutableAttributedString alloc]initWithString:[[NSString alloc] initWithFormat:@"默认价格：%d豆",skuitem.price]];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,5)];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5,[price length]-6)];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange([price length]-1,1)];
    self.priceLabel.attributedText = price;
    //积分
    NSMutableAttributedString* points = [[NSMutableAttributedString alloc]initWithString:[[NSString alloc]  initWithFormat:@"最多可使用%d积分",skuitem.point]];
    [points addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0,5)];
    [points addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(5,[points length]-7)];
    [points addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange([points length]-2,2)];
    self.pointsLabel.attributedText = points;

}

-(void)onActionRules:(UIButton*)btn
{
    SQShopRulesViewController* srvc = [[SQShopRulesViewController alloc]init];
    [self.navigationController pushViewController:srvc animated:YES];
}
-(void)onActionBuy:(UIButton*)btn
{
    if ([Global instance].logined) {
        
        product_sku_t skuitem;
        [[self.skuArr objectAtIndex:self.selectedSku]getValue:&skuitem];
        if (skuitem.stock <=0) {
            //库存不足
            UIAlertView* alterView = [[UIAlertView alloc]initWithTitle:nil message:@"库存不足，您可以选择其他商品！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
            [alterView show];
            return;
        }
        SQGoodsPayViewController* gvc = [[SQGoodsPayViewController alloc]init];
        gvc.productName = [NSString stringWithUTF8String: self.item.title];
        gvc.skuitem = skuitem;
        [self.navigationController pushViewController:gvc animated:YES];
    }
    else{
        SQLoginViewController* lvc = [[SQLoginViewController alloc]init];
        [self.navigationController pushViewController:lvc animated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//读取数据
-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    if (tag == 1) {
        ack_product_detail_t pdetail;
        [data getBytes:&pdetail length:sizeof(pdetail)];
        NSLog(@"pdetail.base.len:%d",pdetail.base.len);
        NSLog(@"data:%d",data.length);
        NSString* msg = @"";
        if (pdetail.base.error == 3063) {
            msg = @"找不到该物品";
            [self.HUD showAnimated:YES whileExecutingBlock:^{
                self.HUD.labelText = msg;
                sleep(2);
                [self.HUD show:NO];
            } completionBlock:^{
            }];
        }else if(pdetail.base.error == ACS_SUCCESS){
            self.skuArr = nil;
            self.skuArr = [NSMutableArray array];
            NSInteger count = pdetail.count;
            NSLog(@"%d",count);
            for (NSInteger i=0; i<count; i++) {
                product_sku_t item;
                [data getBytes:&item range:NSMakeRange(data.length - (count - i)*sizeof(item) - 8,sizeof(item))];
                [self.skuArr addObject:[NSValue value:&item withObjCType:@encode(struct product_sku_t)]];
                NSLog(@"*****************");
                NSLog(@"item:%d",item.point);
                NSLog(@"item:%d",item.stock);
                NSLog(@"item:%d",item.price);
            }
            [self.HUD showAnimated:YES whileExecutingBlock:^{
                [self.HUD show:NO];
            } completionBlock:^{
                [self initview];
            }];
        }
    }
}
-(void)onActionBack:(UIButton*)button
{
    NSLog(@"onaction");
    [super onActionBack:button];
    if (_imageTimer) {
        [_imageTimer invalidate];
        _imageTimer = nil;
    }
}
@end
